package com.itheima.template;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.properties.OssProperties;

import javax.servlet.ServletOutputStream;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

//对象储存服务
//阿里oss对象储存服务对象类
public class OssTemplate {
    private OssProperties ossProperties;

    public OssTemplate(OssProperties ossProperties){
        this.ossProperties=ossProperties;
    }

    public String upload(String filename, InputStream is){
        //获得阿里云地域
        String endpoint=ossProperties.getEndpoint();

        //获得阿里云oss 密钥id 和 解密
        String accessKeyId = ossProperties.getAccessKey();
        String accessKeySecret = ossProperties.getSecret();

        //创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String storePath = new SimpleDateFormat("yyyy/MM/dd")
                .format(new Date()) + "/" + UUID.randomUUID() + filename.substring(filename.lastIndexOf("."));

        System.out.println(storePath);

        ossClient.putObject(ossProperties.getBucketName(),storePath,is);

        String url=ossProperties.getUrl()+storePath;

        //关闭ossclient
        ossClient.shutdown();

        return url;
    }
}
